package com.cy.store.controller;

import com.cy.store.entity.User;
import com.cy.store.service.IUserService;
import com.cy.store.service.ex.InsertEception;
import com.cy.store.service.ex.UsernameDuplicatedException;
import com.cy.store.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/users")
public class UserController extends BaseController {
    @Autowired
    private IUserService userService;

    @RequestMapping("/reg")
    public JsonResult<Void> reg(User user) {
        //修改前
       /* //创建响应结果对象
        JsonResult<Void> result = new JsonResult<>();

        try {
            userService.reg(user);
            result.setState(200);
            result.setMessage("用户注册成功");
        } catch (UsernameDuplicatedException e) {
            result.setState(4000);
            result.setMessage("用户名被占用!");
        } catch (InsertEception e) {
            result.setState(5000);
            result.setMessage("注册产生的未知异常");
        }
        return result;*/

        //修改后
        userService.reg(user);
        return new JsonResult<>(OK);
    }

    /**
     * 用户登录
     *
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/login")
    public JsonResult<User> UserLogin(String username, String password, HttpSession session) {
        User login = userService.login(username, password);

        // 在session中完成数据的绑定(session为全局的)
        session.setAttribute("username", login.getUsername());
        session.setAttribute("uid", login.getUid());

        // 获取session中绑定的项目
        System.out.println(getUidFromSession(session));
        System.out.println(getUsernameFromSession(session));

        return new JsonResult<>(OK, login);
    }

    /**
     * 修改密码
     *
     * @param oldPassword
     * @param newPassword
     * @param session
     * @return
     */
    @RequestMapping("/change_password")
    public JsonResult<Void> changePassword(String oldPassword,
                                           String newPassword,
                                           HttpSession session) {
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        userService.changePassword(uid, username, oldPassword, newPassword);

        return new JsonResult<>(OK);

    }

    /**
     * 修改用户信息时候，进入页面后获取信息
     *
     * @param session
     * @return
     */
    @RequestMapping("/get_by_uid")
    public JsonResult<User> getByUid(HttpSession session) {
        User byUid = userService.getByUid(getUidFromSession(session));
        return new JsonResult<>(OK, byUid);
    }

    /**
     * 修改用户信息
     *
     * @param user
     * @param session
     * @return
     */
    @RequestMapping("/change_info")
    public JsonResult<Void> changeInfo(User user, HttpSession session) {
        Integer uidFromSession = getUidFromSession(session);
        String usernameFromSession = getUsernameFromSession(session);

        userService.changeInfo(uidFromSession, usernameFromSession, user);
        return new JsonResult<>(OK);
    }

    // 设置上传文件的类型
    public static final List<String> AVATAR_TYPE = new ArrayList<>();

    static {
        AVATAR_TYPE.add("images/jpeg");
        AVATAR_TYPE.add("images/png");
        AVATAR_TYPE.add("images/bmp");
        AVATAR_TYPE.add("images/gif");
    }

    /**
     * 修改上传头像
     * MultipartFile接口是springmvc提供一个接口，这个接口为我们包装了获取文件类型的数据。
     *
     * @param session
     * @param file
     * @return
     */
    @RequestMapping("/change_avatar")
    public JsonResult<String> changeAvatar(HttpSession session,
                                           @RequestParam("file") MultipartFile file) throws IOException {
        String upload = session.getServletContext().getRealPath("upload");
        //file对象指向这个路径，file是否存在
        File dir = new File(upload);
        if (!dir.exists()) { //检测目录是否存在
            dir.mkdirs(); //创建当前目录
        }
        //找到这个文件名称，uuid工具来生成一个新字符串作为名字
        String originalFilename = file.getOriginalFilename();
        System.out.println("OriginalFilename" + originalFilename);
        int i = originalFilename.lastIndexOf(".");
        String suffix = originalFilename.substring(i);
        String filename = UUID.randomUUID().toString().toUpperCase() + suffix;

        File dest = new File(dir, filename);//是一个空文件
        //参数file中数据写入到这个dest文件中
        file.transferTo(dest);

        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        //返回头像路径
        String avatar = "/upload" + filename;
        userService.changeAvatar(uid, avatar, username);
        //返回头像路径给前端，将来用于头像展示使用
        return new JsonResult<>(OK, avatar);
    }

}
